//
//  EGMotionLaunchView.m
//  MotionLaunchDemo
//
//  Created by 程登伟 on 16/9/14.
//  Copyright © 2016年 程登伟. All rights reserved.
//

#import "EGMotionLaunchView.h"
#import "EGMotionItemView.h"
#import <CommonCrypto/CommonDigest.h>


#define EGSCREENWIDTH [UIScreen mainScreen].bounds.size.width
#define EGSCREENHEIGHT [UIScreen mainScreen].bounds.size.height
#define EGHORIZONTALITEMCOUNT 3 // 几行
#define EGVERTICALITEMCOUNT 3 // 几列
#define EGITEMWIDTH 50 // 边长


@interface EGMotionLaunchView ()

@property (nonatomic, strong) NSMutableArray *motionViewArr;
@property (nonatomic, strong) UITouch *currentTouch;
@property (nonatomic, copy) EGSuccessBlock success;
@property (nonatomic, copy) EGFaildBlock faild;


@end


@implementation EGMotionLaunchView


+ (instancetype)showMotionViewWithFrame:(CGRect)frame success:(EGSuccessBlock)success faild:(EGFaildBlock)error{
    
    EGMotionLaunchView *motionV = [[EGMotionLaunchView alloc] initWithFrame:frame];
    motionV.success = success;
    motionV.faild = error;
    return motionV;
    
}


- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
        self.backgroundColor = [UIColor clearColor];
        
        self.motionViewArr = [[NSMutableArray alloc] initWithCapacity:0];
        
        [self setUpMotionItems];
        
    }
    return self;
}


- (void)setUpMotionItems{
    
    int p = 0;
    
    for (int i = 0; i < EGHORIZONTALITEMCOUNT; i ++) {
        for (int j = 0; j < EGVERTICALITEMCOUNT; j ++) {
            
            CGFloat itemWidth = EGITEMWIDTH;
            CGFloat itemSpace = (self.frame.size.width - itemWidth*EGHORIZONTALITEMCOUNT)/(EGHORIZONTALITEMCOUNT + 1);
            CGRect itemRect = CGRectMake(itemSpace + (itemWidth + itemSpace)*j, itemSpace + (itemWidth + itemSpace)*i, itemWidth, itemWidth);
            EGMotionItemView *motionItem = [[EGMotionItemView alloc] initWithFrame:itemRect];
            motionItem.tag = p;
            p ++;
            // [motionItem hideSoildCircle:NO];
            [self addSubview:motionItem];
            
        }
    }
}


- (void)drawRect:(CGRect)rect {

    if (self.motionViewArr.count == 0) {
        return;
    }
    
    
    UIBezierPath *bezierPath = [UIBezierPath bezierPath];
    
    EGMotionItemView *itemView = [self containPointItemViewWithTouch];

    [bezierPath moveToPoint:[[self.motionViewArr firstObject] center]];
  
    for (int i = 1; i < self.motionViewArr.count; i ++) {
        [bezierPath addLineToPoint:[[self.motionViewArr objectAtIndex:i] center]];
    }
    
    if (itemView == nil) {
        
        [bezierPath addLineToPoint:[self pointWithCurrentTouch]];

    }
    
    bezierPath.lineWidth = 1;
    bezierPath.lineJoinStyle = kCGLineJoinBevel;
    [[UIColor redColor] set];
    [bezierPath stroke];
    
}


- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    self.currentTouch = [touches anyObject];
    EGMotionItemView *item = [self containPointItemViewWithTouch];
    if (item != nil && ![self.motionViewArr containsObject:item]) {
        [self.motionViewArr addObject:item];
        [self setNeedsDisplay];
    }
    
}


- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    self.currentTouch = [touches anyObject];
    EGMotionItemView *item = [self containPointItemViewWithTouch];
    if (item != nil && ![self.motionViewArr containsObject:item]) {
        [self.motionViewArr addObject:item];
    }
    [self setNeedsDisplay];

}


- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{

    self.currentTouch = [touches anyObject];
    EGMotionItemView *item = [self containPointItemViewWithTouch];
    if (item != nil && ![self.motionViewArr containsObject:item]) {
        [self.motionViewArr addObject:item];
        
        [self setNeedsDisplay];
    }
    
    [self callback];
    
    [self clearMotionItemView];

    [self setNeedsDisplay];
    
}


- (void)clearMotionItemView{
    
    for (EGMotionItemView *item in self.subviews) {
        
        [item hideSoildCircle:YES];
        
    }
    
    [self.motionViewArr removeAllObjects];
    
}


- (EGMotionItemView *)containPointItemViewWithTouch{
    
    for (EGMotionItemView *item in self.subviews) {
        
        CGRect itemRect = [self convertRect:item.frame toView:self];
        CGPoint touchPoint = [self.currentTouch locationInView:self];
        if (CGRectContainsPoint(itemRect, touchPoint)) {
            [item hideSoildCircle:NO];
            return item;
        }
    }
    return nil;
    
}



- (CGPoint)pointWithTouches:(NSSet<UITouch *> *)touches{
    
    UITouch *touch = [touches anyObject];
    CGPoint touchPoint = [touch locationInView:touch.view];
    return touchPoint;
    
}


- (CGPoint)pointWithCurrentTouch{
    
    CGPoint touchPoint = [self.currentTouch locationInView:self];
    return touchPoint;
    
}


- (void)motionLaunchCallbackSuccess:(EGSuccessBlock)success faild:(EGFaildBlock)faild{
    
    self.success = success;
    self.faild = faild;
    
}


- (void)callback{
    
    if (self.motionViewArr.count < 5) {
        self.faild(@"手势密码过短");
        return;
    }
    NSString *pwdStr = @"";
    for (EGMotionItemView *item in self.motionViewArr) {
        pwdStr = [pwdStr stringByAppendingString:[NSString stringWithFormat:@"%ld",item.tag]];
    }
    self.success([self md5:pwdStr]);
    
}


- (NSString *)md5:(NSString *)str
{
    const char *cStr = [str UTF8String];
    unsigned char result[16];
    CC_MD5(cStr, strlen(cStr), result); // This is the md5 call
    return [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
            result[0], result[1], result[2], result[3],
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]
            ];
}



@end
